package com.example.previewvideo.util;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;

import androidx.core.app.ActivityCompat;

import java.io.ByteArrayOutputStream;

/**
 * author : 浪
 * date :2024/9/14 14:54
 * desc:
 */
public class AudioBuffer {
    private static final int BUFFER_SIZE = 1024 * 10; // Adjust size as needed
    private AudioRecord audioRecord;
    private byte[] buffer;
    private boolean isRecording;
    private ByteArrayOutputStream byteArrayOutputStream;

    public void startRecording(Context context) {
        int bufferSize = AudioRecord.getMinBufferSize(44100, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, 44100, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize);
        buffer = new byte[BUFFER_SIZE];
        byteArrayOutputStream = new ByteArrayOutputStream();
        audioRecord.startRecording();
        isRecording = true;

        new Thread(() -> {
            while (isRecording) {
                int read = audioRecord.read(buffer, 0, buffer.length);
                if (read > 0) {
                    byteArrayOutputStream.write(buffer, 0, read);
                }
            }
        }).start();
    }

    public void stopRecording() {
        isRecording = false;
        audioRecord.stop();
        audioRecord.release();
    }

    public byte[] getRecordedData() {
        return byteArrayOutputStream.toByteArray();
    }
}
